import { useState } from 'react'
import { useStore } from '../store/useStore'
import { toast } from 'react-toastify'

export default function AddressManager({ isOpen, onClose, onSelect }) {
  const { addresses, addAddress, updateAddress, deleteAddress, setDefaultAddress } = useStore()
  const [showForm, setShowForm] = useState(false)
  const [editingAddress, setEditingAddress] = useState(null)

  if (!isOpen) return null

  const handleSave = (addressData) => {
    if (editingAddress) {
      updateAddress(editingAddress.id, addressData)
      toast.success('地址已更新！')
    } else {
      addAddress(addressData)
      toast.success('地址已添加！')
    }
    setShowForm(false)
    setEditingAddress(null)
  }

  const handleDelete = (addressId) => {
    if (confirm('确定要删除这个地址吗？')) {
      deleteAddress(addressId)
      toast.success('地址已删除！')
    }
  }

  const handleSetDefault = (addressId) => {
    setDefaultAddress(addressId)
    toast.success('已设为默认地址！')
  }

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 animate-fade-in">
      <div 
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      ></div>

      <div className="relative w-full max-w-3xl max-h-[85vh] glass-effect-dark border border-white/10 rounded-2xl shadow-2xl overflow-hidden animate-scale-in">
        {/* 头部 */}
        <div className="sticky top-0 z-10 glass-effect-dark border-b border-white/10 px-6 py-4">
          <div className="flex items-center justify-between">
            <h2 className="text-2xl font-bold text-white flex items-center space-x-3">
              <svg className="w-8 h-8 text-accent-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
              <span>收货地址</span>
              <span className="text-sm font-normal text-gray-400">
                （{addresses.length} 个）
              </span>
            </h2>
            
            <div className="flex items-center space-x-2">
              <button
                onClick={() => { setEditingAddress(null); setShowForm(true); }}
                className="px-4 py-2 bg-gradient-to-r from-accent-purple to-accent-blue text-white font-semibold rounded-lg hover:scale-105 transition-all duration-300 shadow-lg shadow-accent-purple/30 text-sm flex items-center space-x-1"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
                <span>新增地址</span>
              </button>
              
              <button
                onClick={onClose}
                className="w-10 h-10 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 hover:border-red-500/50 text-gray-400 hover:text-red-400 transition-all duration-300 flex items-center justify-center group"
              >
                <svg className="w-5 h-5 group-hover:rotate-90 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="overflow-y-auto max-h-[calc(85vh-80px)] p-6">
          {!showForm ? (
            // 地址列表
            addresses.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-16">
                <div className="text-8xl mb-6 animate-float">📍</div>
                <p className="text-xl font-semibold text-gray-300 mb-2">暂无收货地址</p>
                <p className="text-sm text-gray-500 mb-6">添加地址后可快速下单</p>
                <button
                  onClick={() => setShowForm(true)}
                  className="px-6 py-3 bg-gradient-to-r from-accent-purple to-accent-blue text-white font-semibold rounded-lg hover:scale-105 transition-all shadow-lg"
                >
                  添加第一个地址
                </button>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {addresses.map((address, index) => (
                  <div
                    key={address.id}
                    className={`relative p-5 rounded-xl border-2 transition-all duration-300 hover:scale-[1.02] card-hover animate-slide-up ${
                      address.isDefault
                        ? 'border-accent-purple bg-accent-purple/10 shadow-lg shadow-accent-purple/30'
                        : 'border-white/10 bg-white/5 hover:border-white/20'
                    }`}
                    style={{ animationDelay: `${index * 0.05}s` }}
                  >
                    {/* 默认标签 */}
                    {address.isDefault && (
                      <div className="absolute top-3 right-3">
                        <span className="px-2 py-1 bg-accent-purple/30 border border-accent-purple/50 text-accent-purple text-xs font-bold rounded-full">
                          默认
                        </span>
                      </div>
                    )}

                    {/* 地址信息 */}
                    <div className="space-y-2 mb-4">
                      <div className="flex items-center space-x-2">
                        <svg className="w-5 h-5 text-accent-blue" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clipRule="evenodd" />
                        </svg>
                        <span className="font-semibold text-white text-lg">{address.name}</span>
                        <span className="text-gray-400 text-sm">{address.phone}</span>
                      </div>
                      
                      <div className="flex items-start space-x-2 text-gray-300">
                        <svg className="w-5 h-5 text-accent-cyan mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                        </svg>
                        <span className="text-sm leading-relaxed">
                          {address.province} {address.city} {address.district}<br/>
                          {address.detail}
                        </span>
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex gap-2">
                      {onSelect && (
                        <button
                          onClick={() => { onSelect(address); onClose(); }}
                          className="flex-1 px-3 py-2 bg-gradient-to-r from-accent-purple to-accent-blue text-white text-sm font-medium rounded-lg hover:scale-105 transition-all shadow-md"
                        >
                          使用此地址
                        </button>
                      )}
                      
                      {!address.isDefault && (
                        <button
                          onClick={() => handleSetDefault(address.id)}
                          className="px-3 py-2 bg-white/5 hover:bg-white/10 border border-white/10 hover:border-accent-purple/50 text-gray-300 hover:text-white text-sm rounded-lg transition-all"
                        >
                          设为默认
                        </button>
                      )}
                      
                      <button
                        onClick={() => { setEditingAddress(address); setShowForm(true); }}
                        className="px-3 py-2 bg-white/5 hover:bg-white/10 border border-white/10 hover:border-accent-blue/50 text-gray-300 hover:text-white text-sm rounded-lg transition-all"
                      >
                        编辑
                      </button>
                      
                      <button
                        onClick={() => handleDelete(address.id)}
                        className="px-3 py-2 bg-red-500/10 hover:bg-red-500/20 border border-red-500/30 hover:border-red-500/50 text-red-400 hover:text-red-300 text-sm rounded-lg transition-all"
                      >
                        删除
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )
          ) : (
            // 地址表单
            <AddressForm
              address={editingAddress}
              onSave={handleSave}
              onCancel={() => { setShowForm(false); setEditingAddress(null); }}
            />
          )}
        </div>
      </div>
    </div>
  )
}

// 地址表单组件
function AddressForm({ address, onSave, onCancel }) {
  const [formData, setFormData] = useState(address || {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  })

  const handleSubmit = (e) => {
    e.preventDefault()
    
    // 验证
    if (!formData.name || !formData.phone) {
      toast.error('请填写姓名和电话')
      return
    }
    
    if (!formData.province || !formData.city || !formData.detail) {
      toast.error('请填写完整地址')
      return
    }
    
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      toast.error('请输入有效的手机号码')
      return
    }
    
    onSave(formData)
  }

  return (
    <form onSubmit={handleSubmit} className="max-w-2xl mx-auto space-y-6 animate-slide-up">
      <h3 className="text-xl font-bold text-white mb-6 flex items-center space-x-2">
        <svg className="w-6 h-6 text-accent-purple" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
        </svg>
        <span>{address ? '编辑地址' : '新增地址'}</span>
      </h3>

      {/* 收货人和电话 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-semibold text-gray-300 mb-2">
            收货人 <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            placeholder="请输入收货人姓名"
            className="w-full px-4 py-3 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-accent-purple/70 focus:ring-2 focus:ring-accent-purple/30 transition-all"
            required
          />
        </div>
        
        <div>
          <label className="block text-sm font-semibold text-gray-300 mb-2">
            手机号码 <span className="text-red-400">*</span>
          </label>
          <input
            type="tel"
            value={formData.phone}
            onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
            placeholder="请输入11位手机号"
            maxLength={11}
            className="w-full px-4 py-3 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-accent-purple/70 focus:ring-2 focus:ring-accent-purple/30 transition-all"
            required
          />
        </div>
      </div>

      {/* 省市区 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <label className="block text-sm font-semibold text-gray-300 mb-2">
            省份 <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={formData.province}
            onChange={(e) => setFormData({ ...formData, province: e.target.value })}
            placeholder="如：北京市"
            className="w-full px-4 py-3 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-accent-purple/70 focus:ring-2 focus:ring-accent-purple/30 transition-all"
            required
          />
        </div>
        
        <div>
          <label className="block text-sm font-semibold text-gray-300 mb-2">
            城市 <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={formData.city}
            onChange={(e) => setFormData({ ...formData, city: e.target.value })}
            placeholder="如：朝阳区"
            className="w-full px-4 py-3 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-accent-purple/70 focus:ring-2 focus:ring-accent-purple/30 transition-all"
            required
          />
        </div>
        
        <div>
          <label className="block text-sm font-semibold text-gray-300 mb-2">
            区县
          </label>
          <input
            type="text"
            value={formData.district}
            onChange={(e) => setFormData({ ...formData, district: e.target.value })}
            placeholder="如：三里屯"
            className="w-full px-4 py-3 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-accent-purple/70 focus:ring-2 focus:ring-accent-purple/30 transition-all"
          />
        </div>
      </div>

      {/* 详细地址 */}
      <div>
        <label className="block text-sm font-semibold text-gray-300 mb-2">
          详细地址 <span className="text-red-400">*</span>
        </label>
        <textarea
          value={formData.detail}
          onChange={(e) => setFormData({ ...formData, detail: e.target.value })}
          placeholder="请填写详细地址，如街道、门牌号、楼层、房间号等"
          rows={3}
          className="w-full px-4 py-3 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-accent-purple/70 focus:ring-2 focus:ring-accent-purple/30 transition-all resize-none"
          required
        />
      </div>

      {/* 设为默认 */}
      <div className="flex items-center space-x-3 p-4 bg-white/5 rounded-lg border border-white/10">
        <input
          type="checkbox"
          id="isDefault"
          checked={formData.isDefault}
          onChange={(e) => setFormData({ ...formData, isDefault: e.target.checked })}
          className="w-5 h-5 rounded bg-white/10 border-white/30 text-accent-purple focus:ring-2 focus:ring-accent-purple/50"
        />
        <label htmlFor="isDefault" className="text-sm text-gray-300 cursor-pointer select-none">
          设为默认收货地址
        </label>
      </div>

      {/* 按钮 */}
      <div className="flex gap-3 pt-4 border-t border-white/10">
        <button
          type="button"
          onClick={onCancel}
          className="flex-1 px-6 py-3 bg-white/5 hover:bg-white/10 border border-white/10 hover:border-white/20 text-white rounded-lg transition-all duration-300 font-semibold hover:scale-105"
        >
          取消
        </button>
        
        <button
          type="submit"
          className="flex-1 px-6 py-3 bg-gradient-to-r from-accent-purple via-accent-blue to-accent-cyan text-white font-semibold rounded-lg hover:scale-105 transition-all duration-300 shadow-lg shadow-accent-purple/50 hover:shadow-xl"
        >
          保存地址
        </button>
      </div>
    </form>
  )
}

